import {
  Body,
  Controller,
  Delete,
  Get,
  NotFoundException,
  Patch,
  Post,
  Query,
  UploadedFile,
  UseGuards,
  UseInterceptors,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { UserService } from '../service/user.service';
import { JwtGuard } from '../guards/jwt.guard';
import { FindUserParamDto } from '../dto/user/find-user.dto';
import { FindUserPipe } from '../pipes/user/find-user.pipe';
import { CreateUserDto } from '../dto/user/create-user.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBody,
  ApiConsumes,
} from '@nestjs/swagger';
import { FileObject, FileUploadDto } from '../dto/upload/file.dto';
import { UpdateUserDto } from '../dto/user/update-user.dto';

@ApiTags('用户管理')
@Controller('user')
@UseGuards(JwtGuard)
@UsePipes(new ValidationPipe({ transform: true }))
export class UserController {
  constructor(private userService: UserService) {}

  @ApiOperation({ summary: '获取用户列表' })
  @ApiResponse({ status: 200, description: '成功返回用户列表' })
  @Get()
  async getUsers(
    @Query(FindUserPipe) { pageNum, pageSize }: FindUserParamDto,
    @Query('keyword') keyword?: string,
  ) {
    const data = await this.userService.getUsers(pageNum, pageSize, keyword);
    return {
      status: 200,
      data,
    };
  }

  @ApiOperation({ summary: '上传用户头像' })
  @ApiResponse({ status: 200, description: '上传成功' })
  @Post('upload')
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: '用户头像上传',
    type: FileUploadDto,
  })
  @UseInterceptors(FileInterceptor('avatar'))
  async upload(@UploadedFile() file) {
    return {
      status: 200,
      message: '上传成功',
      data: {
        url: `/${(file as FileObject).filename}`,
      },
    };
  }

  @ApiOperation({ summary: '创建新用户' })
  @ApiResponse({ status: 200, description: '创建成功' })
  @Post()
  async createUser(@Body() createUserDto: Partial<CreateUserDto>) {
    await this.userService.createUser(createUserDto);
    return {
      status: 200,
      message: '新增用户成功',
    };
  }

  @ApiOperation({ summary: '更新用户信息' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @ApiResponse({ status: 404, description: '更新失败' })
  @Patch()
  async updateUser(@Body() createUserDto: Partial<UpdateUserDto>) {
    const updateUser = await this.userService.updateUser(createUserDto);
    if (updateUser.acknowledged) {
      return {
        status: 200,
        message: '更新成功',
      };
    } else {
      throw new NotFoundException('更新失败');
    }
  }

  @ApiOperation({ summary: '删除用户' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @ApiResponse({ status: 404, description: '删除失败' })
  @Delete()
  async deleteUser(@Query('id') id: string) {
    const res = await this.userService.deleteUser(id);
    if (res.acknowledged) {
      return {
        status: 200,
        message: '删除成功',
      };
    } else {
      throw new NotFoundException('删除失败');
    }
  }
}
